package com.example.nginx;

import java.io.*;
import java.nio.file.*;
import java.util.Properties;
import java.util.logging.Logger;

/**
 * 配置加载器
 * 负责从配置文件加载日志生成器和轮转管理器的配置
 */
public class ConfigurationLoader {
    private static final Logger logger = Logger.getLogger(ConfigurationLoader.class.getName());
    
    private static final String DEFAULT_CONFIG_FILE = "config.properties";
    private static final String DEFAULT_OUTPUT_FILE = "access.log";
    private static final int DEFAULT_LOGS_PER_SECOND = 10;
    private static final boolean DEFAULT_ROTATION_ENABLED = true;
    private static final long DEFAULT_MAX_FILE_SIZE = 10 * 1024 * 1024; // 10MB
    private static final LogRotationManager.TimeRotationInterval DEFAULT_TIME_INTERVAL = 
            LogRotationManager.TimeRotationInterval.DAY;
    private static final int DEFAULT_MAX_FILES = 7;
    private static final String DEFAULT_FILE_PATTERN = "yyyy-MM-dd";
    private static final String DEFAULT_ROTATION_DIRECTORY = "logs";
    
    private final Properties properties;
    
    public ConfigurationLoader() {
        this(DEFAULT_CONFIG_FILE);
    }
    
    public ConfigurationLoader(String configFile) {
        this.properties = new Properties();
        loadConfiguration(configFile);
    }
    
    /**
     * 加载配置文件
     */
    private void loadConfiguration(String configFile) {
        try {
            File file = new File(configFile);
            if (!file.exists()) {
                logger.warning("配置文件不存在，使用默认配置: " + configFile);
                setDefaultValues();
                return;
            }
            
            try (InputStream input = new FileInputStream(file)) {
                properties.load(input);
                logger.info("成功加载配置文件: " + configFile);
            }
            
        } catch (IOException e) {
            logger.severe("加载配置文件失败: " + e.getMessage() + "，使用默认配置");
            setDefaultValues();
        }
    }
    
    /**
     * 设置默认值
     */
    private void setDefaultValues() {
        properties.setProperty("output.file", DEFAULT_OUTPUT_FILE);
        properties.setProperty("logs.per.second", String.valueOf(DEFAULT_LOGS_PER_SECOND));
        properties.setProperty("log.rotation.enabled", String.valueOf(DEFAULT_ROTATION_ENABLED));
        properties.setProperty("log.rotation.max.size", String.valueOf(DEFAULT_MAX_FILE_SIZE));
        properties.setProperty("log.rotation.time.interval", DEFAULT_TIME_INTERVAL.name());
        properties.setProperty("log.rotation.max.files", String.valueOf(DEFAULT_MAX_FILES));
        properties.setProperty("log.rotation.file.pattern", DEFAULT_FILE_PATTERN);
        properties.setProperty("log.rotation.directory", DEFAULT_ROTATION_DIRECTORY);
    }
    
    /**
     * 获取输出文件路径
     */
    public String getOutputFile() {
        return properties.getProperty("output.file", DEFAULT_OUTPUT_FILE);
    }
    
    /**
     * 获取每秒生成日志条数
     */
    public int getLogsPerSecond() {
        try {
            return Integer.parseInt(properties.getProperty("logs.per.second", String.valueOf(DEFAULT_LOGS_PER_SECOND)));
        } catch (NumberFormatException e) {
            logger.warning("无效的logs.per.second配置，使用默认值: " + DEFAULT_LOGS_PER_SECOND);
            return DEFAULT_LOGS_PER_SECOND;
        }
    }
    
    /**
     * 是否启用日志轮转
     */
    public boolean isRotationEnabled() {
        return Boolean.parseBoolean(properties.getProperty("log.rotation.enabled", String.valueOf(DEFAULT_ROTATION_ENABLED)));
    }
    
    /**
     * 获取最大文件大小
     */
    public long getMaxFileSize() {
        try {
            // 将MB转换为字节
            long sizeInMB = Long.parseLong(properties.getProperty("log.rotation.max.size", String.valueOf(DEFAULT_MAX_FILE_SIZE / (1024 * 1024))));
            return sizeInMB * 1024 * 1024;
        } catch (NumberFormatException e) {
            logger.warning("无效的log.rotation.max.size配置，使用默认值: " + DEFAULT_MAX_FILE_SIZE);
            return DEFAULT_MAX_FILE_SIZE;
        }
    }
    
    /**
     * 获取时间轮转间隔
     */
    public LogRotationManager.TimeRotationInterval getTimeInterval() {
        try {
            String interval = properties.getProperty("log.rotation.time.interval", DEFAULT_TIME_INTERVAL.name());
            return LogRotationManager.TimeRotationInterval.valueOf(interval.toUpperCase());
        } catch (IllegalArgumentException e) {
            logger.warning("无效的log.rotation.time.interval配置，使用默认值: " + DEFAULT_TIME_INTERVAL);
            return DEFAULT_TIME_INTERVAL;
        }
    }
    
    /**
     * 获取最大文件数量
     */
    public int getMaxFiles() {
        try {
            return Integer.parseInt(properties.getProperty("log.rotation.max.files", String.valueOf(DEFAULT_MAX_FILES)));
        } catch (NumberFormatException e) {
            logger.warning("无效的log.rotation.max.files配置，使用默认值: " + DEFAULT_MAX_FILES);
            return DEFAULT_MAX_FILES;
        }
    }
    
    /**
     * 获取文件命名模式
     */
    public String getFilePattern() {
        return properties.getProperty("log.rotation.file.pattern", DEFAULT_FILE_PATTERN);
    }
    
    /**
     * 获取轮转目录
     */
    public String getRotationDirectory() {
        return properties.getProperty("log.rotation.directory", DEFAULT_ROTATION_DIRECTORY);
    }
    
    /**
     * 打印当前配置
     */
    public void printConfiguration() {
        logger.info("当前配置:");
        logger.info("  输出文件: " + getOutputFile());
        logger.info("  每秒日志条数: " + getLogsPerSecond());
        logger.info("  日志轮转启用: " + isRotationEnabled());
        logger.info("  最大文件大小: " + getMaxFileSize() + " 字节");
        logger.info("  时间轮转间隔: " + getTimeInterval());
        logger.info("  最大文件数量: " + getMaxFiles());
        logger.info("  文件命名模式: " + getFilePattern());
        logger.info("  轮转目录: " + getRotationDirectory());
    }
}